<template>
  <div class='searchSuggestion'>
    <van-cell
      v-for="(item, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search', item)"
    >
      <div slot="title" v-html="hightlightSearchSuggestion(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/user'
import { debounce } from 'lodash'

export default {
  name: 'searchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  watch: {
    searchText: {
      // debounce:该函数会从上一次被调用后，延迟 wait 毫秒后调用 func 方法，解决防抖问题
      handler: debounce(async function () {
        const { data } = await getSearchSuggestions(this.searchText)
        this.suggestions = data.data.options
      }, 300),
      // 该回调将会在侦听开始之后被立即调佣
      immediate: true
    }
  },
  methods: {
    hightlightSearchSuggestion (item) {
      return item.replace(
        new RegExp(this.searchText, 'gi'),
        `<span style="color:red;">${this.searchText}</span>`
      )
    }
  }
}
</script>
<style lang='less' scoped></style>
